/**
 * @file 04_rename.c
 * @author your name (you@domain.com)
 * @brief rename demo
 * @version 0.1
 * @date 2023-03-06
 *
 * @copyright Copyright (c) 2023
 *
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    {
        int fd = open("../../a.tmp", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
        if (fd < 0)
        {
            perror("open");
            exit(1);
        }
        close(fd);
    }
    {
        int fd = open("./b.tmp", O_RDONLY);
        if (fd >= 0)
        {
            printf("file already exist. \n");
            close(fd);
            exit(1);
        }
    }

    int res = rename("../../a.tmp", "./b.tmp");
    if (res < 0)
    {
        perror("rename");
        exit(1);
    }

    {
        int fd = open("./b.tmp", O_RDONLY);
        if (fd < 0)
        {
            perror("open");
            exit(1);
        }
        close(fd);
    }

    unlink("./b.tmp");
    printf("rename test ok.\n");

    return 0;
}